package middlewares

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"net/url"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

const appSecret = "zhongman-admin-secret-0524"

type SignAuthMiddlewareParam struct {
	AppId     string `json:"appId"`
	NonceStr  string `json:"nonceStr"`
	Timestamp string `json:"timestamp"`
	Sign      string `json:"sign"`
}

func SignAuthMiddleware(c *gin.Context) {
	param := SignAuthMiddlewareParam{}
	dingo.ErrorIf(c.ShouldBindBodyWith(&param, binding.JSON)).Unwrap()
	//body, _ := ioutil.ReadAll(c.Request.Body)
	////读取请求数据
	//_ = json.Unmarshal(body, &param)
	if param.Sign == "" || param.AppId == "" || param.Timestamp == "" || param.NonceStr == "" {
		Response(c)("签名校验失败", CodeError, nil)(BadRequest) // 没有参数
		c.Abort()
		return
	}
	//校验签名
	str := "appId=" + param.AppId + "&nonceStr=" + param.NonceStr + "&timestamp=" + param.Timestamp

	signStr := url.QueryEscape(str)

	s := []byte(signStr)
	//zhongman-admin-secret-0524
	key := []byte(appSecret)
	m := hmac.New(sha256.New, key)
	m.Write(s)
	signature := hex.EncodeToString(m.Sum(nil))

	if signature != param.Sign {
		Response(c)("签名校验失败", CodeError, false)(BadRequest) // 校验签名
		c.Abort()
		return
	}
	c.Next()
}
